package com.xiaoming.api;

import com.xiaoming.dao.TokenRepository;
import com.xiaoming.dao.UserRepository;
import com.xiaoming.entity.Token;
import com.xiaoming.entity.User;
import com.xiaoming.service.CodeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@RestController
public class TokenController {
    @Autowired
    private TokenRepository tokenRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CodeMessage messageService;

    @GetMapping("/register/{email}/{password}/{code}")
    @Transactional
    public String register(@PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code) throws Exception {

        boolean registered = isRegistered(email);
        if (registered) {
            return "当前用户已注册！";
        }
        int validator = messageService.validate(email, code);
        if (validator == 1) {
            return "验证码错误！";
        }
        if (validator == 2) {
            return "验证码超时！";
        }
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userRepository.save(user);
        return "注册成功";
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) throws Exception {
        List<User> users = userRepository.findByEmail(email);
        if (users.size() > 0) {
            return true;
        }
        return false;
    }

    @GetMapping("/login/{email}/{password}")
    @Transactional
    public String login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response) {
        List<User> users = userRepository.findByEmailAndPassword(email, password);
        if (users.size() == 0) {
            return "账号或密码错误";
        }
        String uuid = UUID.randomUUID().toString();
        Token token = new Token();
        token.setToken(uuid);
        token.setEmail(email);
        tokenRepository.save(token);
        Cookie cookie = new Cookie("sc-token", uuid);
        cookie.setPath("/");
        response.addCookie(cookie);
        return email;
    }

    @GetMapping("/info/{token}")
    public String login(@PathVariable("token") String cookie) {
        Token token = tokenRepository.findByToken(cookie);
        if (token == null) {
            return null;
        }
        return token.getEmail();
    }
}
